package controller;

/**
 *
 * @author Sujen
 */
import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import model.Lid;
import org.hibernate.Session;
import org.hibernate.Transaction;
import persistence.SessionManager;
import security.ActivationKey;
import util.ValidateMail;

public class WijzigGebruikerController extends HttpServlet {

    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        HttpSession sessie = request.getSession();

// is user ingelogd?
        if (null == sessie.getAttribute("currentUser")) {
            // User IS NOT logged in....    
            System.out.println("User is niet ingelogd - Redir naar Login pagina");
            response.sendRedirect("Login");
        } else {
            // User IS logged in.... 
            System.out.println("Redir naar wijzigGebruiker.jsp");
            response.sendRedirect("wijzigGebruiker.jsp");
        }
    }   
    
      
    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        HttpSession sessie = request.getSession();

        Lid lid = (Lid) sessie.getAttribute("currentUser");

        String fname = new String();
        String tussenvoegsel = new String();
        String lname = new String();
        String password = new String();
        String state = new String();
        String huisnummer = new String();
        String postalcode = new String();
        String emailAdres = new String();
        String dname = new String();
        boolean validOrInvalid = true;
        Date nu = new Date();
        Date geboortedatum = new Date();
        DateFormat dateformat = new SimpleDateFormat("dd/MM/yyyy");

        Session session = null;
        session = SessionManager.openSession();
        Transaction tx = session.beginTransaction();

        if (request.getParameter("fname") != null && !request.getParameter("fname").isEmpty()) {
            fname = request.getParameter("fname");
        } else {
            request.setAttribute("naam", "Naam is leeg");
            validOrInvalid = false;
        }
        if (request.getParameter("lname") != null && !request.getParameter("lname").isEmpty()) {
            lname = request.getParameter("lname");
        } else {
            request.setAttribute("name", "Achternaam is leeg");
            validOrInvalid = false;
        }
        if (request.getParameter("geboortedatum") != null && !request.getParameter("geboortedatum").isEmpty()) {
            try{
            geboortedatum = dateformat.parse(request.getParameter("geboortedatum"));
            } catch (ParseException ex) {
            Logger.getLogger(RitToevoegenController.class.getName()).log(Level.SEVERE, null, ex);
        }
        } else {
            request.setAttribute("geboortedatum", "Geboortedatum is leeg");
            validOrInvalid = false;
        }
        if (request.getParameter("password") != null && !request.getParameter("password").isEmpty()) {
            password = request.getParameter("password");
        } else {
            request.setAttribute("word", "Wachtwoord is incorrect");
            validOrInvalid = false;
        }
        if (!request.getParameter("state").equals("")) {
            state = request.getParameter("state");
        } else {
            request.setAttribute("state", "Provincie is leeg");
            validOrInvalid = false;
        }
        if (request.getParameter("emailAdres") != null && !request.getParameter("emailAdres").isEmpty() && ValidateMail.isEmail(request.getParameter("emailAdres"))) {
            emailAdres = request.getParameter("emailAdres");
        } else {
            request.setAttribute("mail", "E-mail is incorrect");
            validOrInvalid = false;
        }
        if (request.getParameter("postalcode") != null && !request.getParameter("postalcode").isEmpty()) {
            postalcode = request.getParameter("postalcode");
        } else {
            request.setAttribute("post", "Postcode is leeg");
            validOrInvalid = false;
        }
        if (request.getParameter("huisnummer") != null && !request.getParameter("huisnummer").isEmpty()) {
            huisnummer = request.getParameter("huisnummer");
        } else {
            request.setAttribute("huis", "Huisnummer is leeg");
            validOrInvalid = false;
        }

        tussenvoegsel = request.getParameter("insertion");

        if (validOrInvalid == true) {
            if (tussenvoegsel.isEmpty() && request.getParameter("insertion") == null || tussenvoegsel.equals("")) {
                dname = fname.concat(" ").concat(lname);
            } else {
                dname = fname.concat(" ").concat(tussenvoegsel).concat(" ").concat(lname);
            }

            lid.setLidVnaam(fname);
            lid.setLidTussenvoegsel(tussenvoegsel);
            lid.setLidAnaam(lname);
            lid.setLidGeboortedatum(geboortedatum);
            lid.setLidDisplaynaam(dname);
            lid.setLidPassword(password);
            lid.setLidEmail(emailAdres);
            lid.setLidHuisnummer(huisnummer);
            lid.setLidProvincie(state);
            lid.setLidPostcode(postalcode);
            lid.setLidRegistered(nu);
            lid.setLidActivationkey(ActivationKey.generateActivationKey());
            lid.setRolId(2);
            lid.setLidActivated(true);

            session.update(lid);
            tx.commit();
            session.close();

            response.sendRedirect("mijnDryves.jsp");
        } else {
            String address = "/wijzigGebruiker.jsp";
            RequestDispatcher dispatcher = request.getRequestDispatcher(address);
            dispatcher.forward(request, response);
        }
    }
}
